import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime

mode = True
drawing = False
ix, iy = -1, -1

def mouse_callback(event, x, y, flags, param):
    global drawing, ix, iy
    if event == cv.EVENT_LBUTTONDOWN:
        ix, iy = x, y
        drawing = True

    if event == cv.EVENT_LBUTTONUP:
        drawing = False

    if event == cv.EVENT_MOUSEMOVE:
        if drawing:
            if mode:
                cv.rectangle(img, (ix, iy), (x, y), (255, 0, 0), 1, cv.LINE_4)
            else:
                cv.circle(img, ((ix + x)//2, (iy + y)//2), abs(x - ix) // 2, (0, 0, 255), 1, cv.LINE_8)

# img = np.ones([480, 640, 3], dtype=np.uint8) * 255
img = np.full([480, 640, 3], 255, dtype=np.uint8)
title = "M to toggle mode, ESC to exit"
cv.namedWindow(title)
cv.setMouseCallback(title, mouse_callback)

while(True):
    cv.imshow(title, img)
    k = cv.waitKey(50) & 0xFF
    if k == ord('m') or k == ord('M'):
        mode = not mode
    elif k == 27 or k == ord('q') or k == ord('Q'):
        break

cv.destroyAllWindows()
